﻿using System;
using System.Collections.Generic;
using SdmxMl.Structure;
using SdmxMl.Manager;
using System.Windows.Forms;

namespace SdmxMl.UC
{
    public partial class UcAgencyRef : UserControl
    {
        private OrganisationType agency;
        private bool _isFinal;

        public bool IsFinal
        {
            set 
            { 
                _isFinal = value;
                comboBoxAgency.Enabled = _isFinal == false;
            }
        }
        public UcAgencyRef()
        {
            InitializeComponent();
        }

        public override string Text
        {
            get
            {
                return comboBoxAgency.Text;
            }
            set
            {
                comboBoxAgency.Text = value;
                comboBoxAgency.Items.Clear();

                UpdateAgencyRef(value);
                List<OrganisationType> agencyList = ReferenceManager.GetAgencyList();
                agencyList.Sort();
                comboBoxAgency.Items.AddRange(agencyList.ToArray());
            }
        }

        private void UpdateAgencyRef(string id)
        {
            if (string.IsNullOrEmpty(id) == false)
            {
                agency = ReferenceManager.LocateAgency(id);
            }
            else
                agency = null;

            buttonRefError.Visible = agency == null;
        }

        private void comboBoxAgency_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateAgencyRef(comboBoxAgency.Text);
        }

        private void buttonNavigate_Click(object sender, EventArgs e)
        {
            // Navigate 
            if (agency != null)
                NavigationManager.RequestNavigation(agency);
            else
            {
                // load configured NSI agency list and try to navigate
                try
                {
                    if (SdmxMl.Msg.HeaderGenerator.NSI_OrgScheme != null)
                    {
                        SmManager sm = new SmManager();
                        sm.PutArtefact(SdmxArtefactType.OrganisationSchemes, SdmxMl.Msg.HeaderGenerator.NSI_OrgScheme);
                        NavigationManager.LoadFromSmManager(sm);
                        UpdateAgencyRef(comboBoxAgency.Text);
                        if (agency != null)
                            NavigationManager.RequestNavigation(agency);
                    }
                }
                catch { }
            }
        }

        private void comboBoxAgency_TextUpdate(object sender, EventArgs e)
        {
            UpdateAgencyRef(comboBoxAgency.Text);         
        }
    }
}
